<!-- 组织机构历史快照详情 -->
<template>
  <ConditionBox :margin-bottom="20">
    <template #left>
      <a-space>
        <span>组织机构({{ flatData.length }})</span>
        <span>|</span>
        <div>
          <a-dropdown
            :popup-max-height="false"
            v-model="treeLevel"
            @select="handleTreeLevelSelect"
          >
            <span style="cursor: pointer"
              >展开{{ treeLevel !== 4 ? treeLevel : '全部' }}级<icon-down
                style="color: #165dff"
              />
            </span>
            <template #content>
              <a-doption :value="1">1级</a-doption>
              <a-doption :value="2">2级</a-doption>
              <a-doption :value="3">3级</a-doption>
              <a-doption :value="4">全部</a-doption>
            </template>
          </a-dropdown>
        </div>
      </a-space>
      <a-input-search
        v-model="nameSearch"
        placeholder="请输入组织名称"
        :style="{
          width: '220px'
        }"
        search-button
        @search="onSearch"
        @press-enter="onSearch"
      >
        <icon-search />
      </a-input-search>
    </template>
    <template #right>
      <a-button type="outline" @click="exportSettingVisible = true"
        >导出</a-button
      >
    </template>
  </ConditionBox>
  <TableTurn
    :tableData="getTableData"
    :args="args"
    ref="tableRef"
    :isShowPagination="false"
  >
    <a-table-column title="架构图" :width="100">
      <template #cell="{ record }">
        <div>
          <a-tooltip content="点击跳转到对应的架构图页面">
            <icon-font
              type="icon-group-def"
              :size="26"
              style="cursor: pointer"
              @click="goStructurePic(record.id)"
            />
          </a-tooltip>
        </div>
      </template>
    </a-table-column>
    <TableControlShow
      :selectedHeader="selectedHeader"
      :showCtlCodeArr="showCtlCodeArr"
      :specialCtlCode="['C30BBF36A5AF541F7A2657671DEE2EDD6']"
    >
      <template #custom="record">
        <div
          v-if="
            record.controlData.ctlCode === 'C30BBF36A5AF541F7A2657671DEE2EDD6'
          "
          :style="{
            paddingLeft:
              record.cellData.level > 2
                ? '32px'
                : (record.cellData.level - 1) * 16 + 'px',
            cursor: 'pointer'
          }"
        >
          {{ record.cellData[record.controlData.ctlCode] }}
        </div>
      </template>
    </TableControlShow>
    <a-table-column title="是否启用" :width="100" data-index="enable">
      <template #cell="{ record }">
        <a-tag
          class="enable"
          :color="
            record.enable === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
          "
          :style="{
            color:
              record.enable === 1
                ? `rgb(var(--green-6))`
                : 'rgb(var(--danger-6))',
            '--enable':
              record.enable === 1
                ? `rgb(var(--green-6))`
                : 'rgb(var(--danger-6))'
          }"
        >
          {{ record.enable === 1 ? '启用' : '停用' }}
        </a-tag>
      </template>
    </a-table-column>
    <!-- <a-table-column :width="150" fixed="right">
      <template #title>
        <a-tooltip content="表头设置">
          <icon-font
            type="icon-filter-def"
            :size="26"
            :style="{
              marginRight: '10px',
              cursor: 'pointer'
            }"
            @click="isFilter"
          />
        </a-tooltip>
        <a-tooltip content="表头设置">
          <icon-font
            type="icon-setting-def"
            :size="26"
            :style="{
              cursor: 'pointer'
            }"
            @click="isHeaderSetting"
          />
        </a-tooltip>
      </template>
      <template #cell="{ record }">
        <a-tooltip content="档案详情">
          <icon-font
            type="icon-details-def"
            :size="26"
            :style="{
              cursor: 'pointer'
            }"
            @click="goDetail(record.id)"
          />
        </a-tooltip>
      </template>
    </a-table-column> -->
  </TableTurn>
  <FormHeaderControlSetting
    v-model:visible="setting"
    title="组织表头设置"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :forbidList="forbidList"
    :orginHeaderList="orginHeaderList.headerListCode"
  ></FormHeaderControlSetting>
  <ExportControlSetting
    v-model:visible="exportSettingVisible"
    title="组织导出设置"
    :result-list="exportHeaderList"
    @headerSave="exportSave"
    :forbidList="exportyForbidList"
  >
  </ExportControlSetting>
</template>

<script lang="tsx" setup>
import mitter from '@/utils/mitt';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import {
  GetOrganizationList,
  GetWorkPlaceList,
  ExportOrganizationListNew
} from '@/apis/management/organization/organizationManagement';
import { OrganizationPatternSearch } from '@/apis/management/organization/baseSetting/organizationalType';
import {
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import { GetBusinessModalData } from '@/apis/controltotal';
import { Message } from '@arco-design/web-vue';

const props = withDefaults(
  // 参数说明
  defineProps<{
    data: any; // 传进来的数据
  }>(),
  {
    data: []
  }
);
const router = useRouter();

let nameSearch = ref(''); //名称搜索框

let tableRef = ref(); // 储存table的ref
let flatData = ref<any>([]); // 储存扁平化的数据
let loading = ref(true);
// 新增表头
const addHeader = async () => {
  try {
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCFA65A09668D949CEB25F5AD3B233F6E0'
    })) as any;

    let headerListCode: any = [];
    console.log(children, 'children');

    children.forEach((item1: any) => {
      const { subRelDetail } = item1.subDetail;
      subRelDetail.forEach((item2: any) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 1,
      headerListCode: headerListCode.join(',')
    });

    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true,
  indentSize: 0
});

let treeLevel = ref(3); // 展开多少层子树，初始展开3层

// 选择展开子树层级事件
const handleTreeLevelSelect = (val: number) => {
  treeLevel.value = val;
};

// 处理数据展开层级
const handleLevel = () => {
  if (tableRef.value) {
    tableRef.value.currExpandedKeys = [];
    flatData.value.forEach((item: any) => {
      if (item.level < 4) {
        if (item.level < treeLevel.value)
          tableRef.value.currExpandedKeys.push(item.id);
      } else {
        tableRef.value.currExpandedKeys.push(item.id);
      }
    });
  }
};

watch(
  () => treeLevel.value,
  (val) => {
    handleLevel();
  }
);

let organizationList = ref();

// 根据组织名称模糊搜索过滤函数
const maptree = (treeData: any, val: string) => {
  let filteredData: any = [];
  treeData.forEach((node: any) => {
    // 如果是组织名称C30BBF36A5AF541F7A2657671DEE2EDD6
    if (node['C30BBF36A5AF541F7A2657671DEE2EDD6'].includes(val)) {
      filteredData.push(node);
    } else {
      if (node.children && node.children.length > 0) {
        let filteredChildren = maptree(node.children, val);
        if (filteredChildren.length > 0) {
          let updatedNode = {
            ...node,
            children: filteredChildren
          };
          filteredData.push(updatedNode);
        }
      }
    }
  });
  return filteredData;
};

let deptList: any = ref([]); // 储存组织列表信息
// 获取表格数据
const getTableData = async () => {
  try {
    if (props.data.length > 0) {
      loading.value = false;
      flatData.value = flatTree(dataTreeFilter(props.data));
      organizationList.value = maptree(
        dataTreeFilter(props.data),
        nameSearch.value
      );
      deptList.value = flatTree(dataTreeFilter(props.data));
      handleLevel();
      return Promise.resolve(organizationList.value);
    } else return Promise.resolve([]);
  } catch (error: unknown) {
    console.log(error);
  }
};

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal.length > 0) tableRef.value.loadData();
  }
);

// 搜索数据
const onSearch = async () => {
  tableRef.value.loadData();
};

let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据
let organizationTypeList = ref<any>([]); // 组织类型数据
let workPlaceList = ref<any>([]); // 工作地点数据
let userList = ref<any>([]); // 人员列表数据

/*
  获取数据
  分别为
    表头数据
    组织类型列表
    工作地点
    人员列表
    控件数据
*/
const getData = async () => {
  try {
    const userId = +(localStorage.getItem('userId') as string);
    const [
      headerSettingRes,
      organizationPatternRes,
      workPlaceListRes,
      businessModalDataRes
    ] = await Promise.all([
      GetHeaderSetting({
        ownerFuncType: 1,
        userId
      }),
      OrganizationPatternSearch({
        pageNumber: 0,
        pageSize: -1
      }),
      GetWorkPlaceList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetBusinessModalData({
        funcCode: 'SER_FUNCFA65A09668D949CEB25F5AD3B233F6E0'
      })
    ]);
    orginHeaderList.value = headerSettingRes;
    organizationTypeList.value = organizationPatternRes.content;
    workPlaceList.value = workPlaceListRes.content;
    // userList.value = userListRes.content;

    headerSetting.value = [];
    const headerChildren = businessModalDataRes.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      headerSetting.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    exportHeaderList.value = headerSetting.value;
    if (headerSettingRes.headerListCode.length < 1) {
      addHeader();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将组织名称移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C30BBF36A5AF541F7A2657671DEE2EDD6'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});
// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 1,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'C3D33FA57216F4968BDE51C31D623FC09',
  'C073F4F41C46D4CA3AF3BEC1F51A8F410',
  'CBD9EC71A717B47E6A844F084E6035353',
  'CE009C2E2B542409D815F0D3D54FE0E2B',
  'C37521ED1EF684F1F96B08FF8852E6030',
  'C80DC4DFCBE0B4B2F83DA0C353E521691',
  'CA6BD9CC1C99D4D13AD4F5009EF4F9586'
];

// 点击去往组织结构图
const goStructurePic = (id: number) => {
  mitter.emit('changeStructure', id);
};

let filter = ref(false); // 判断是否显示排序筛选
// 显示编辑输入框筛选按钮
const isFilter = () => {
  filter.value = !filter.value;
};

let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let forbidList = [
  'C30BBF36A5AF541F7A2657671DEE2EDD6', // 组织名称
  'CB1AAC9E508714223BA4D1596FE690877', // 组织编码
  'C3D33FA57216F4968BDE51C31D623FC09', // 组织类型
  'CD25749DBA68E4BF3BCA616DD63751CB7', // 编制人数
  'CB0C63F38283045F58FFF1B1EABE5D151', // 组织负责人
  'CE009C2E2B542409D815F0D3D54FE0E2B' // 工作地点
]; // 必选的表头
// 是否显示表头
const isHeaderSetting = async () => {
  try {
    // const { header } = await GetHeaderSetting({
    //   type: 1,
    //   userId: +(localStorage.getItem('userId') as string)
    // });
    // headerList.value = header;
    // console.log('zzz', headerList.value);

    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

const getHeaderData = () => {
  try {
    // return GetHeaderSetting({
    //   ownerFuncType: 1,
    //   userId: +(localStorage.getItem('userId') as string)
    // });
    return headerSetting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

let exportSettingVisible = ref(false);
let exportHeaderList = ref(); // 接口获取过来的原始表头数据
let exportyForbidList = [
  'C30BBF36A5AF541F7A2657671DEE2EDD6', // 组织名称
  'CB1AAC9E508714223BA4D1596FE690877', // 组织编码
  'C3D33FA57216F4968BDE51C31D623FC09', // 组织类型
  'CD25749DBA68E4BF3BCA616DD63751CB7', // 编制人数
  'CB0C63F38283045F58FFF1B1EABE5D151', // 组织负责人
  'CE009C2E2B542409D815F0D3D54FE0E2B' // 工作地点
]; // 必选的表头

const exportSave = async (used: any) => {
  try {
    if (selectedList.value.length === 0) {
      Message.error('请至少选择一项导出！');
      return;
    } else {
      let code: any = [],
        name: any = [];
      used.forEach((item: any) => {
        code.push(item.code);
        name.push(item.name);
      });
      const res = await ExportOrganizationListNew({
        code: code + '',
        name: name + '',
        ids: selectedList.value + ''
      });
      if (selectedList.value.length === 1) {
        downloadExcelFile(res, `${selectedListData.value[0].name}信息导出`);
      } else {
        downloadExcelFile(
          res,
          `${selectedListData.value[0].name}等组织信息导出`
        );
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
// 弄出一个小的圆形
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
